package com.xxja.order.auth.controller;

import com.xxja.order.auth.user.pojo.User;
import com.xxja.order.auth.user.service.UserService;
import com.xxja.order.utils.ResponseBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    private static final String COOKIE_NAME = "user";

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid @RequestBody User user) {
        String token = this.userService.register(user);
        return ResponseBuilder.okEntity(token);
    }
    @GetMapping("ds")
    public String test() {
        return "false";
    }
    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<Void> login(@RequestParam("name") String name, @RequestParam("password") String password, HttpServletResponse response) {
        String token = this.userService.query(name, password);
        if (token == null) {
            return ResponseBuilder.responseEntity("返回token失败，请重新登录", 400);
        }
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResponseBuilder.responseEntity(token, 200);
    }

}
